import 'package:dio/dio.dart';
import 'package:fsharing/core/models/message.dart';
import 'package:fsharing/core/services/api.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';

class MessageQueryModel extends ViewModel {
  final Api api;
  final List<Message> _list = [];
  String _errorMessage;
  List<Message> _messages;

  MessageQueryModel(this.api) : super() {
    _initData();
  }

  List get list => _list;

  String get errorMessage => _errorMessage;

  List<Message> get messages => _messages;

  Future<ViewState> _initData() async {
    viewState = ViewState.busy;
    try {
      _messages = await api.messageQuery(0, cancelToken);
      _list.clear();
      _list.addAll(_messages);
      if (_list.isEmpty) {
        throw '暂无数据';
      }
      viewState = ViewState.success;
    } catch (e) {
      _errorMessage = e is DioError ? e.message : e.toString();
      viewState = ViewState.error;
    }
    return viewState;
  }

  Future<ViewState> refreshData() async {
    try {
      _messages = await api.messageQuery(0, cancelToken);
      _list.clear();
      _list.addAll(_messages);
      if (_list.isEmpty) {
        throw '暂无数据';
      }
      viewState = ViewState.success;
    } catch (e) {}
    return viewState;
  }

  Future<ViewState> loadData() async {
    try {
      _messages = await api.messageQuery(_list.length ~/ 10, cancelToken);
      _list.addAll(_messages);
      viewState = ViewState.success;
    } catch (e) {}
    return viewState;
  }
}
